package com.lxl.xm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxl.xm.common.DailyEarning;
import com.lxl.xm.common.DailyRegistration;
import com.lxl.xm.model.entity.AdCampaign;
import com.lxl.xm.model.entity.Student;
import com.lxl.xm.service.AdCampaignService;
import com.lxl.xm.mapper.AdCampaignMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* @author 86135
* @description 针对表【ad_campaign( 广告投放表)】的数据库操作Service实现
* @createDate 2024-01-31 16:32:41
*/
@Service
public class AdCampaignServiceImpl extends ServiceImpl<AdCampaignMapper, AdCampaign>
    implements AdCampaignService{

    @Resource
    AdCampaignMapper adCampaignMapper;

    @Override
    public List<DailyEarning> getEarningLast7Days() {
        List<DailyEarning> result = new ArrayList<>();

        // 获取近七天的日期范围
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date()); // 设置当前日期
        calendar.add(Calendar.DAY_OF_YEAR, -6); // 将当前日期往前推六天，使其为七天前的日期
        Date startDate = calendar.getTime(); // 开始日期为七天前的日期

        // 查询每天的注册人数
        for (int i = 0; i < 7; i++) {
            LambdaQueryWrapper<AdCampaign> wrapper = Wrappers.lambdaQuery();
            wrapper.ge(AdCampaign::getStartDate, startDate)
                    .lt(AdCampaign::getStartDate, addDays(startDate, 1)); // 查询指定日期当天注册的学生
            long clicks = adCampaignMapper.selectCount(wrapper);
            Long earning = (long) (clicks*0.01);
            result.add(new DailyEarning(startDate, earning));
            // 将日期往后推一天
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            startDate = calendar.getTime();
        }
        return result;
    }
    private Date addDays(Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, days);
        return calendar.getTime();
    }

    @Override
    public List<AdCampaign> getTopCampaignsByClicks(int limit) {
        QueryWrapper<AdCampaign>queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("clicks");
        return this.list(queryWrapper.last("LIMIT"+" "+limit));
    }
}




